﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Goods.Entity;
using NewRetail.Application.Components.Warehouse;
using NewRetail.Application.Components.Warehouse.Entity;
using NewRetail.Application.Core;
using Serilog;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("discount-goods")]
    public class PromoteSaleDiscountGoodsController : BaseController<PromoteSalesDiscountGoods>
    {
        private readonly IDiscountService _discountService;
        public PromoteSaleDiscountGoodsController(IDiscountService discountService)
        {
            this._discountService = discountService;
        }

        public override async Task<ResponseEntity<PagedResultDto<PromoteSalesDiscountGoods>>> QueryPaging([FromBody] PagingRequestDto dto)
        {
            var res = await base.QueryPaging(dto);

            if (res.Data?.Items?.Any() ?? false)
            {
                var db = await this.Repo.GetDbContextAsync();
                await db.AttachData<GoodsInfo, PromoteSalesDiscountGoods>(res.Data.Items,
                    x => x.goodsID,
                    (m, arr) => m.GoodsInfo = arr.FirstOrDefault());
                await db.AttachData<PromoteSalesDiscount, PromoteSalesDiscountGoods>(res.Data.Items,
                    x => x.discountID,
                    (m, arr) => m.PromoteSalesDiscount = arr.FirstOrDefault());
            }

            return res;
        }

        [HttpPost("add-multiple")]
        public async Task<ResponseEntity<PromoteSalesDiscountGoods[]>> AddMultiple([FromBody] PromoteSalesDiscountGoods[] data)
        {
            data.Should().NotBeNullOrEmpty();
            foreach (var m in data)
            {
                this.EntityHelper.InitEntity(m);
            }

            var ids = data.Select(x => x.goodsID).Distinct().ToArray();

            await this.Repo.DeleteAsync(x => ids.Contains(x.goodsID), autoSave: true);
            await this.Repo.InsertManyAsync(data, autoSave: true);

            return new ResponseEntity<PromoteSalesDiscountGoods[]>().SetData(data);
        }

        #region 单品打折商品导入
        /// <summary>
        /// 单品打折商品导入
        /// </summary>
        /// <param name="inputDto"></param>
        /// <remarks>表头   注：一定要有一行表头行 </remarks>
        /// <returns></returns>
        [HttpPost("importDiscountGoodsData")]
        public async Task<IActionResult> ImportDiscountGoodsDataAsync([FromForm] ImportDiscountGoodsReqDto inputDto)
        {
            var data = new ResponseEntity<bool>();
            try
            {
                var formFile = inputDto.Attachment;
                var discountId = inputDto.DiscountID;
                var warehouseId = inputDto.warehouseID;
                var result = await _discountService.ImportDiscountGoods(formFile, discountId, warehouseId);
                if (!string.IsNullOrWhiteSpace(result.Item2))
                    return Ok(data.SetError(result.Item2));

                return Ok(data.SetData(result.Item1));
            }
            catch (Exception e)
            {
                var errMsg = "导入异常：" + e.Message;
                Log.Error(errMsg);
                return Ok(data.SetError(errMsg));
            }
        }
        #endregion
    }
}
